// 模拟菜品数据
//const menuItems = [
//    { id: 1, name: "宫保鸡丁", description: "经典川菜，鸡肉鲜嫩，花生香脆，麻辣可口", price: 4.2, category: "热菜", image: "" },
//    { id: 2, name: "水煮鱼", description: "新鲜鱼片配以豆芽和辣椒，麻辣鲜香", price: 68, category: "热菜", image: "./img/logo.png" },
//    { id: 3, name: "北京烤鸭", description: "传统北京风味，皮脆肉嫩，配以薄饼和甜面酱", price: 128, category: "热菜", image: "./img/logo.png" },
//    { id: 4, name: "麻婆豆腐", description: "麻辣鲜香，豆腐嫩滑，下饭绝配", price: 36, category: "热菜", image: "./img/logo.png" },
//    { id: 5, name: "拍黄瓜", description: "清爽凉菜，蒜香浓郁，开胃解腻", price: 18, category: "凉菜", image: "./img/logo.png" },
//    { id: 6, name: "老醋花生", description: "香脆花生米配以老陈醋，酸爽开胃", price: 22, category: "凉菜", image: "./img/logo.png" },
//    { id: 7, name: "西湖牛肉羹", description: "鲜香滑嫩的牛肉羹，杭州特色汤品", price: 38, category: "鱼粉", image: "" },
//    { id: 8, name: "扬州炒饭", description: "粒粒分明，配料丰富，经典淮扬风味", price: 32, category: "主食", image: "./img/logo.png" },
//    { id: 9, name: "鲜榨西瓜汁", description: "新鲜西瓜现榨，清凉解渴", price: 28, category: "饮品", image: "./img/logo.png" },
//    { id: 10, name: "酸梅汤", description: "传统酸梅汤，酸甜可口，生津止渴", price: 20, category: "饮品", image: "./img/logo.png" },
//    { id: 11, name: "红烧狮子头", description: "肉丸鲜嫩多汁，酱汁浓郁，淮扬名菜", price: 58, category: "热菜", image: "./img/logo.png" },
//    { id: 12, name: "清蒸鲈鱼", description: "鱼肉鲜嫩，清淡爽口，保留原汁原味", price: 78, category: "热菜", image: "./img/logo.png" },
//    { id: 13, name: "清蒸鲈鱼", description: "鱼肉鲜嫩，清淡爽口，保留原汁原味", price: 78, category: "热菜", image: "./img/logo.png" },
//    { id: 14, name: "清蒸鲈鱼", description: "鱼肉鲜嫩，清淡爽口，保留原汁原味", price: 78, category: "热菜", image: "./img/logo.png" },
//    { id: 15, name: "清蒸鲈鱼", description: "鱼肉鲜嫩，清淡爽口，保留原汁原味", price: 78, category: "热菜", image: "./img/logo.png" }
//];

// 存储订单数据
let order = {};
// 在文件顶部声明变量（原const改为let）
let menuItems = [];
let categories = [];

// 初始化页面
// 在文件顶部添加分类数组
//const categories = [...new Set(menuItems.map(item => item.category))];

// 修改初始化代码
document.addEventListener('DOMContentLoaded', () => {
    // 新增API请求
    fetch('/menu/list')
        .then(response => response.json())
        .then(data => {
            menuItems = data; // 更新菜单数据
            categories = [...new Set(data.map(item => item.category))]; // 重新生成分类
            renderCategories();
            renderMenu();
            updateOrderSummary();
        })
        .catch(error => console.error('Error fetching menu:', error));
});

// 新增分类渲染函数
function renderCategories() {
    const categoriesContainer = document.querySelector('.menu-categories');
    categoriesContainer.innerHTML = `
        <button class="category-btn active" data-category="all">全部</button>
        ${categories.map(category => `
            <button class="category-btn" data-category="${category}">${category}</button>
        `).join('')}
    `;

    // 添加分类点击事件
    categoriesContainer.querySelectorAll('.category-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelector('.category-btn.active').classList.remove('active');
            this.classList.add('active');
            renderMenu(this.dataset.category);
        });
    });
}

// 修改 renderMenu 函数，添加分类过滤参数
function renderMenu(filterCategory = 'all') {
    const menuItemsContainer = document.getElementById('menuItems');
    menuItemsContainer.innerHTML = '';
    
    const filteredItems = filterCategory === 'all' 
        ? menuItems 
        : menuItems.filter(item => item.category === filterCategory);
    
    filteredItems.forEach(item => {
        const menuItemElement = document.createElement('div');
        menuItemElement.className = 'menu-item';
        menuItemElement.innerHTML = `
            <img src="${item.image || './img/logo.png'}" alt="${item.name}">
            <div class="menu-item-content">
                <h3>${item.name}</h3>
                <div class="item-bottom">
                    <div class="price">¥${item.price.toFixed(2)}</div>
                </div>
            </div>
        `;
        // 添加整个菜单项的点击事件
        menuItemElement.addEventListener('click', (event) => {
            if (!event.target.closest('.add-btn')) {
                addToOrder(item.id);
            }
        });
        menuItemsContainer.appendChild(menuItemElement);
    });
}

// 修改添加菜品逻辑（替换原有addToOrder函数）
// 修改 addToOrder 函数，移除动画相关代码
function addToOrder(itemId) {
    const item = menuItems.find(i => i.id === itemId);
    const uniqueId = Date.now();
    order[uniqueId] = { 
        ...item,
        quantity: 1 
    };
    renderOrderItems();
    updateOrderSummary();
}

// 修改订单项渲染逻辑（替换原有renderOrderItems函数）
function renderOrderItems() {
    const orderItemsContainer = document.getElementById('orderItems');
    
    if (Object.keys(order).length === 0) {
        orderItemsContainer.innerHTML = `
            <div class="empty-order">
                <svg class="basket-icon" viewBox="0 0 24 24" width="48" height="48">
                    <path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/>
                </svg>
                <p>您的订单是空的<br>请从右侧菜单选择菜品</p>
            </div>`;
        return;
    }
    
    orderItemsContainer.innerHTML = '';
    
    for (const uniqueId in order) {
        const item = order[uniqueId];
        const orderItemElement = document.createElement('div');
        orderItemElement.className = 'order-item';
        orderItemElement.innerHTML = `
            <div class="item-info">
                <img src="${item.image || './img/logo.png'}" alt="${item.name}">
                <div class="item-details">
                    <h3>${item.name}</h3>
                    <p>¥${item.price.toFixed(2)}</p>
                </div>
            </div>
            <div class="item-quantity">
                <button class="delete-btn" onclick="removeItem(${uniqueId})">
                    <svg class="trash-icon" viewBox="0 0 24 24" width="16" height="16">
                        <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                    </svg>
                </button>
            </div>`;
        orderItemsContainer.appendChild(orderItemElement);
    }
}

// 新增删除功能
function removeItem(uniqueId) {
    delete order[uniqueId];
    renderOrderItems();
    updateOrderSummary();
}

// 修改菜品数量
function changeQuantity(itemId, change) {
    if (order[itemId]) {
        order[itemId].quantity += change;
        
        if (order[itemId].quantity <= 0) {
            delete order[itemId];
        }
        
        renderOrderItems();
        updateOrderSummary();
    }
}

// 更新订单摘要
function updateOrderSummary() {
    let itemCount = 0;
    let subtotal = 0;
    
    for (const itemId in order) {
        const item = order[itemId];
        itemCount += item.quantity;
        subtotal += item.price * item.quantity;
    }
    
    document.getElementById('itemCount').textContent = itemCount;
    document.getElementById('subtotal').textContent = `¥${subtotal.toFixed(2)}`;
}

// 在文件末尾添加以下代码

// 清空订单函数
function clearOrder() {
    if (Object.keys(order).length === 0) {
        return;
    }
    
    if (confirm('确定要清空所有已选菜品吗？')) {
        order = {};
        renderOrderItems();
        updateOrderSummary();
    }
}

// 添加清空按钮点击事件
function initClearButton() {
    const clearBtn = document.querySelector('.clear-btn');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            clearOrder();
        });
    }
}

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initClearButton();
});

// 提交订单函数
function submitOrder() {
    if (Object.keys(order).length === 0) {
        alert('请先选择菜品');
        return;
    }
    
    // 计算总金额和菜品数量
    let totalAmount = 0;
    let itemCount = 0;
    const orderItems = [];
    
    for (const uniqueId in order) {
        const item = order[uniqueId];
        totalAmount += item.price * item.quantity;
        itemCount += item.quantity;
        
        orderItems.push({
            name: item.name,
            description: item.description,
            price: item.price,
            quantity: item.quantity,
            category: item.category,
            image: item.image
        });
    }
    
    const orderData = {
        totalAmount: totalAmount,
        itemCount: itemCount,
        items: orderItems
    };
    
    // 发送订单到后端
    fetch('/menu/submit-order', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(orderData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('订单提交成功！订单号: ' + data.orderId);
            // 清空订单
            order = {};
            renderOrderItems();
            updateOrderSummary();
        } else {
            alert('订单提交失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('订单提交失败');
    });
}

// 添加打印按钮点击事件
function initPrintButton() {
    const printBtn = document.querySelector('.print-btn');
    if (printBtn) {
        printBtn.addEventListener('click', function() {
            // 调用提交订单函数
            submitOrder();
        });
    }
}

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initPrintButton();
});